
/*
 * shhbox Namespace
 */
var shhbox = {};

/*
 * shhbox.Service
 */
shhbox.Service = OClass({
	
	makeRequest: function(path, contextPrefix, options) {
	
		options.callback = options.callback || "shhbox.Service.processResponse";
		options.context = options.context || contextPrefix + ":" + shhbox.Service.currentContext++;
		
		var url = 
			shhbox.Service.SERVICE_LOCATION 
			+ path + ".json"
			+ shhbox.Service.toParams(options);
		
		shhbox.Service.addScriptRequest(url);
		
	},
	
	getRecentMessages: function(options) {
	
		this.makeRequest("/messages", "getRecentMessages", options);
		
	}
	
});

/*
 * Adds a script tag (to a JSONP request) to the head
 */
shhbox.Service.addScriptRequest = function(url){
	var head = document.getElementsByTagName("head")[0];
	script = document.createElement('script');
	script.id = 'dynamic-script';
	script.type = 'text/javascript';
	script.src = url;
	head.appendChild(script);
};

/*
 * Turns an object into a querystring
 */
shhbox.Service.toParams = function(o) {
	
	var paramStr = "?";
	objx(o).each(function(k, v){
		paramStr += v + "=" + k + "&";
	});
	return paramStr.substr(0, paramStr.length-1);
	
};

/*
 * shhbox.Service.processResponse
 * Processes the response of a request
 */
shhbox.Service.processResponse = function(response, context) {
	
	// raise the events
	if (response.w) {

		// raise the onResponse event
		shhbox.Service.onResponse(response, context);
		
		if (context.substr(0,17) == "getRecentMessages") {
			shhbox.Service.onMessages(response, context);
		}
		
	} else {
	
		// raise the error event
		shhbox.Service.onError(response, context);
		
	}
	
}

/*
 * shhbox.Service events
 */
OEvent(shhbox.Service, "onResponse");
OEvent(shhbox.Service, "onError");
OEvent(shhbox.Service, "onMessages");

/*
 * Constants and settings
 */
shhbox.Service.SERVICE_LOCATION = "http://shhbox.com/api/v1";
shhbox.Service.currentContext = 1;